package com.emergency.embackend.service.impl;

import com.emergency.embackend.common.PageParams;
import com.emergency.embackend.entity.Share;
import com.emergency.embackend.entity.ShareComment;
import com.emergency.embackend.exception.EmException;
import com.emergency.embackend.mapper.ShareDataMapper;
import com.emergency.embackend.service.DataViewService;
import com.emergency.embackend.service.OperateService;
import com.emergency.embackend.service.ShareDataService;
import com.emergency.embackend.utils.RedisConstants;
import com.emergency.embackend.utils.ShareStatusEnum;
import com.emergency.embackend.utils.UserHolder;
import com.emergency.embackend.vo.ShareDetailVO;
import com.emergency.embackend.vo.ShareVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShareDataServiceImpl implements ShareDataService {
    @Autowired
    private ShareDataMapper shareDataMapper;
    @Autowired
    private OperateService operateService;
    @Autowired
    private DataViewService dataViewService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //添加分享信息
    @Override
    public void add(Share share) {
        Long userId = UserHolder.getUser().getId();
        shareDataMapper.add(share, userId);
    }
    //删除分享信息
    @Override
    public void delete(Long id) {
        shareDataMapper.delete(id);
        stringRedisTemplate.delete(RedisConstants.SHARE_LIKE_COUNT+id);
        stringRedisTemplate.delete(RedisConstants.VIEW_SHARE_COUNT_KEY+id);
        stringRedisTemplate.delete(RedisConstants.VIEW_SHARE_REPEAT_KEY+id);
    }
    //修改分享信息
    @Override
    public void update(Share share) {
        shareDataMapper.update(share);
    }
    //获取用户自己分享信息
    @Override
    public PageInfo getShareByUser(Long userId, PageParams pageParams) {
        PageHelper.startPage(pageParams.getPageNum(), pageParams.getPageSize());
        List<ShareDetailVO> resList = shareDataMapper.page(userId);

        resList.forEach(e -> {
            e.setStatus(ShareStatusEnum.getStatus(e.getStatus()));
            //获取总的浏览量
            e.setViewCount(dataViewService.getViewCount(RedisConstants.VIEW_SHARE_COUNT_KEY + e.getId()) + e.getViewCount());
            e.setLikeCount(operateService.getLikeOrCollectCount(RedisConstants.SHARE_LIKE_COUNT+e.getId()));
        });
        PageInfo pageInfo = new PageInfo(resList);
        return pageInfo;
    }

    @Override
    public PageInfo getAll(PageParams pageParams) {
        PageHelper.startPage(pageParams.getPageNum(), pageParams.getPageSize());
        List<Share> resList = shareDataMapper.pageAll();
        resList.forEach(e -> {
            e.setViewCount(dataViewService.getViewCount(RedisConstants.VIEW_SHARE_COUNT_KEY + e.getId()) + e.getViewCount());
            e.setLikeCount(operateService.getLikeOrCollectCount(RedisConstants.SHARE_LIKE_COUNT+e.getId()));
        });
        PageInfo pageInfo = new PageInfo(resList);
        return pageInfo;
    }
    //根据时间获取分享信息
    @Override
    public PageInfo pageTime(PageParams pageParams) {
        PageHelper.startPage(pageParams.getPageNum(), pageParams.getPageSize());
        List<ShareDetailVO> resList =shareDataMapper.pageTime();
        resList.forEach(e -> {
                e.setViewCount(dataViewService.getViewCount(RedisConstants.VIEW_SHARE_COUNT_KEY + e.getId()) + e.getViewCount());
                e.setLikeCount(operateService.getLikeOrCollectCount(RedisConstants.SHARE_LIKE_COUNT+e.getId()));
        });
        PageInfo pageInfo = new PageInfo(resList);
        return pageInfo;
    }
    //获取某个分享信息
    @Override
    public ShareDetailVO getOne(Long id) {
        ShareDetailVO data = shareDataMapper.getOne(id);
        if (data == null) {
            throw new EmException("401", "内容丢失，请咨询管理员");
        }
        ShareDetailVO detailVO = new ShareDetailVO();
        BeanUtils.copyProperties(data,detailVO);
        if (UserHolder.getUser() != null) {
            operateService.addViews(id, null, '2');
        } else {
            operateService.addViews(id, UserHolder.getUser().getId(), '2');
        }
        //获取所有的评论数据
        detailVO.setCommentList(getCommentByShareId(id));
        //修改浏览量
        detailVO.setViewCount(dataViewService.getViewCount(RedisConstants.VIEW_SHARE_COUNT_KEY + id) + data.getViewCount());
        detailVO.setLikeCount(operateService.getLikeOrCollectCount(RedisConstants.SHARE_LIKE_COUNT+data.getId()));
        return detailVO;
    }

    private List<ShareComment> getCommentByShareId(Long shareId) {
        //获取所有数据
       List<ShareComment>  commentList =shareDataMapper.getComment(shareId);
        List<ShareComment> rootList = new ArrayList<>();
        Long rootId = 0L;
        //获取根节点数据
        commentList.forEach(e->{
            if(rootId.equals(e.getRootId())){
                e.setChildComment(new ArrayList<>());
                rootList.add(e);
            }
        });
        //遍历根节点并且构造数据
        rootList.forEach(root->{
            root.getChildComment().add(findChildComment(commentList,root));
        });
        return rootList;
    }

    private ShareComment findChildComment(List<ShareComment> commentList, ShareComment father) {
        //初始化当前的list
        father.setChildComment(new ArrayList<>());
       commentList.forEach(e->{
           //如果当前节点的父节点是father,则需要加入list中
            if(e.getRootId().equals(father.getShareCommentId())){
                father.getChildComment().add(findChildComment(commentList,e));
            }
        });
       return father;
    }

    //获取审核信息
    @Override
    public PageInfo underReview(PageParams pageParams) {
        PageHelper.startPage(pageParams.getPageNum(), pageParams.getPageSize());
        List<Share> resList = shareDataMapper.underView();
        resList.forEach(e -> {
                e.setViewCount(dataViewService.getViewCount(RedisConstants.VIEW_SHARE_COUNT_KEY + e.getId()) + e.getViewCount());
                e.setLikeCount(operateService.getLikeOrCollectCount(RedisConstants.SHARE_LIKE_COUNT+e.getId()));
        });
        PageInfo pageInfo = new PageInfo<>(resList);
        return pageInfo;
    }
    //修改审核信息
    @Override
    public void changeStatus(char status, Long id) {
        shareDataMapper.addStatusLog(status,id);
        shareDataMapper.changeStatus(status,id);
    }


    @Override
    public ShareDetailVO getUserOne(Long id) {
        ShareDetailVO data = shareDataMapper.getUserOne(id);
        if (data == null) {
            throw new EmException("401", "内容丢失，请咨询管理员");
        }
        ShareDetailVO detailVO = new ShareDetailVO();
        BeanUtils.copyProperties(data,detailVO);
        if (UserHolder.getUser() != null) {
            operateService.addViews(id, null, '2');
        } else {
            operateService.addViews(id, UserHolder.getUser().getId(), '2');
        }
        //获取所有的评论数据
        detailVO.setCommentList(getCommentByShareId(id));
        //修改浏览量
        detailVO.setViewCount(dataViewService.getViewCount(RedisConstants.VIEW_SHARE_COUNT_KEY + id) + data.getViewCount());
        detailVO.setLikeCount(operateService.getLikeOrCollectCount(RedisConstants.SHARE_LIKE_COUNT+data.getId()));
        return detailVO;
    }

    @Override
    public void addComment(ShareComment shareComment) {
        Long userId=UserHolder.getUser().getId();
        shareDataMapper.addComment(userId,shareComment);
    }

    @Override
    public List<ShareVO> getHistory(Long userId) {
       List<ShareVO> resList = shareDataMapper.getHistory(userId);
       if(resList!=null && resList.size()!=0){
           return resList;
       }
       return null;
    }


}
